package com.tsj.protocol;

import com.tsj.common.Invocation;
import org.apache.commons.io.IOUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @Author tsj
 * @Date 2023/11/15/15:26
 */
public class HttpClient {

    public String send(String hostName, Integer port, Invocation invocation) {
        try {
            // 用户的配置
            URL url = new URL("http",hostName,port,"/");
            HttpURLConnection httpUrlConnection = (HttpURLConnection) url.openConnection();
            httpUrlConnection.setRequestMethod("POST");
            httpUrlConnection.setDoOutput(true);

            OutputStream outputStream = httpUrlConnection.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(outputStream);

            oos.writeObject(invocation);
            oos.flush();
            oos.close();

            InputStream inputStream = httpUrlConnection.getInputStream();
            String result = IOUtils.toString(inputStream);
            return  result;
        }catch (Exception e){
            e.printStackTrace();
        }

        return "null";
    }
}
